#include "LeString.h"

#include <cstdio>
#include <cstring>
#include <vector>
#include <cstdarg>

namespace
{
	std::string ReplaceInternal(const std::string& sourceString, const char* charToReplace, size_t charToReplaceCount, const char* replaceWith)
	{
		std::string outString(sourceString);
		// Check if start and end are the same, if so, just return the string
		if (strcmp(charToReplace, replaceWith) != 0)
		{
			std::size_t indexOfCharToReplace = outString.find(charToReplace);
			while (indexOfCharToReplace != std::string::npos)
			{
				outString = outString.replace(indexOfCharToReplace, charToReplaceCount, replaceWith);
				indexOfCharToReplace = outString.find(charToReplace, indexOfCharToReplace +1);
			}

		}
		return outString;
	}
}

le::String::String()
{

}

le::String::~String()
{

}

std::string le::String::Replace( const std::string& str, const char* charToReplace, const char* replaceWith )
{
	return ReplaceInternal(str, charToReplace, strlen(charToReplace), replaceWith);
}

std::string le::String::Replace( const std::string& str, const std::string& toReplace, const std::string& replaceWith )
{
	return ReplaceInternal(str, toReplace.c_str(), toReplace.size(), replaceWith.c_str());
}

std::string le::String::Replace( const std::string& str, char charToReplace, char replaceWith )
{
	return ReplaceInternal(str, &charToReplace, 1, &replaceWith);
}

std::string le::String::Format( const char* format, ... )
{
	std::vector<char> buffer(32);
	va_list args;
	va_start(args, format);
#ifdef WIN32
	while(vsnprintf_s((&buffer[0]), buffer.size(), _TRUNCATE, format, args) < 0)
	{
#else
	while(vsnprintf((&buffer[0]), buffer.size(), format, args) < 0)
	{
#endif
		buffer.resize(buffer.size() * 2);
	}
	va_end(args);

	return std::string(buffer.begin(), buffer.end());
}
